import { BarChart } from 'echarts/charts';
import {
  TitleComponent,
  TooltipComponent,
  GridComponent,
  LegendComponent,
} from 'echarts/components';
import * as echarts from 'echarts/core';
import { CanvasRenderer } from 'echarts/renderers';
import { useEffect, useRef } from 'react';

import useWindowWidth from '@/hooks/event/use-window-width';

echarts.use([
  TitleComponent,
  TooltipComponent,
  GridComponent,
  LegendComponent,
  BarChart,
  CanvasRenderer,
]);

interface UserBarChartProps {
  data: {
    date: string;
    userCount: number;
    newUserCount: number;
    newUserComparison: number;
    overlapUserCount: number;
    overlapUserComparison: number;
  }[];
  title?: string;
  height?: number;
}

const UserBarChart = ({ data, title, height = 200 }: UserBarChartProps) => {
  const { isPc } = useWindowWidth();
  const chartRef = useRef(null);
  const chartInstance = useRef(null) as any;

  useEffect(
    function setupChart() {
      if (!chartRef.current || !data.length) return;

      // 初始化图表
      chartInstance.current = echarts.init(chartRef.current);

      // 计算Y轴最大值（增加10%的缓冲空间）
      const maxUserCount = Math.max(...data.map((item) => item.userCount));
      const yAxisMax = maxUserCount > 0 ? Math.ceil(maxUserCount * 1) + 1 : 1;

      // 根据设备类型格式化 X 轴标签：移动端去掉年份，避免拥挤
      const xAxisLabels = isPc
        ? data.map((item) => item.date)
        : data.map((item) => (item.date && item.date.length >= 7 ? item.date.slice(5) : item.date));

      // 图表配置
      const option = {
        title: {
          text: title,
          left: 'center',
          textStyle: {
            color: '#333',
            fontSize: 16,
            fontWeight: 'bold',
          },
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow',
          },
          backgroundColor: 'rgba(255, 255, 255, 0.6)',
          borderColor: 'rgba(255, 255, 255, 0.6)',
          borderWidth: 1,
          borderRadius: 8,
          textStyle: {
            color: '#333',
          },
          extraCssText:
            'backdrop-filter: blur(3px); -webkit-backdrop-filter: blur(10px); box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);',
          formatter: (params: any) => {
            // 获取当前数据点的完整数据
            const [{ dataIndex }] = params as Array<{ dataIndex: number }>;
            const item = data[dataIndex];

            // 计算对比值的箭头和颜色
            const getComparisonStyle = (value: number) => {
              if (value > 0) {
                return `
                <span style="
                  color: #52c41a; 
                  display: inline-flex; 
                  align-items: center;
                  gap: 4px;
                ">
                  +${value}
                </span>
              `;
              }
              if (value < 0) {
                return `
                <span style="
                  color: #ff4d4f; 
                  display: inline-flex; 
                  align-items: center;
                  gap: 4px;
                ">
                  ${value}
                </span>
              `;
              }
              return `<span style="color: #999;">-</span>`;
            };

            // 格式化数字
            const formatNumber = (num: number) => num.toLocaleString();
            // <div style="color:'#87919B'; margin-bottom: 5px;border-bottom: 1px solid #f0f0f0; padding-bottom: 10px;">${
            //   item.date
            // }</div>

            return `
            <div   
            style="padding:4px;width:195px;
          
            ">
              <div style="display: flex; justify-content: space-between;color: #20242A;margin-bottom: 5px;border-bottom: 1px solid #F2F3F3; padding-bottom: 10px;">
                <span>总用户数：</span>
                <b>${formatNumber(item.userCount)}</b>
              </div>
           
                <div style="display: flex;align-items: center;justify-content: space-between; margin-bottom: 5px;;">
                 <div style="display: flex;align-items: center;">
                  <div style="width:10px; height: 10px; background: #5FD5FD;margin-right: 8px;"></div>
                  <span style="color: #20242A; font-weight: bold;">新増用户：</span>
                 </div>
                  <b>${formatNumber(item.newUserCount)}</b>
                </div>
                
                <div style="display: flex; justify-content: space-between; margin-bottom: 5px;">
                  <span style="margin-left: 18px;">对比昨日：</span>
                  ${getComparisonStyle(item.newUserComparison)}
                </div>
              
                <div style="display: flex; justify-content: space-between; margin-bottom: 5px; ">
                 <div style="display: flex;align-items: center;">
                  <div style="width:10px; height: 10px; background: #2171F8;margin-right: 8px;"></div>
                            <span style="color: #20242A; font-weight: bold;">重叠用户：</span>
                 </div>
         
                  <b>${formatNumber(item.overlapUserCount)}</b>
                </div>
                
                <div style="display: flex; justify-content: space-between;">
                  <span style="margin-left: 18px;">对比昨日：</span>
                  ${getComparisonStyle(item.overlapUserComparison)}
                </div>
            </div>
          `;
          },
        },
        legend: {
          top: 0,
          left: 15,
          icon: 'roundRect',
          itemWidth: 14,
          itemHeight: 14,
          itemGap: 15,
          itemStyle: { borderRadius: 16 },
        },
        grid: {
          left: '3%',
          right: '3%',
          bottom: '0%', // 为图例留出空间
          top: 40,
          containLabel: true,
        },
        xAxis: {
          type: 'category',
          data: xAxisLabels,
          axisLine: {
            lineStyle: {
              color: '#ccc',
            },
          },
          axisLabel: {
            color: '#87919D',
            fontSize: 12,
            interval: data.length > 15 ? 2 : 0, // 强制显示所有标签
            // 当标签过多时旋转并调整位置
            formatter: (value: string) => {
              // 当数据点超过7个时旋转标签
              if (data.length > 7) {
                return `{rotate|${value}}`;
              }
              return value;
            },
            rich: {
              rotate: {
                rotate: 45,
                align: 'right',
                verticalAlign: 'middle',
                padding: [0, 5, 0, 0],
              },
            },
          },
        },
        yAxis: {
          type: 'value',
          nameTextStyle: {
            color: '#666',
            fontSize: 12,
          },
          axisLine: {
            show: false,
            lineStyle: {
              color: '#ccc',
            },
          },
          splitLine: {
            lineStyle: {
              color: '#f0f0f0',
              type: 'dashed',
            },
          },
          axisLabel: {
            color: '#87919D',
            fontSize: 12,
          },
          max: yAxisMax, // 设置Y轴最大值（增加缓冲空间）
        },
        series: [
          {
            name: '重叠用户',
            type: 'bar',
            barGap: '-100%', // 关键设置：使柱子重叠
            data: data.map((item) => item.overlapUserCount),
            itemStyle: {
              color: '#1E6FFA',
              borderRadius: [8, 8, 0, 0],
              // 禁用悬停时的样式变化
              emphasis: {
                color: '#1E6FFA',
              },
            },
            // 优化：避免嵌套三元表达式，使用 if-else 逻辑
            barWidth: (() => {
              if (data.length === 7) {
                return '20%';
              }
              if (data.length > 15) {
                return '60%';
              }
              return '8%';
            })(), // 减小柱子宽度
          },
          {
            name: '新增用户',
            type: 'bar',
            barGap: '-100%', // 关键设置：使柱子重叠
            data: data.map((item) => item.newUserCount),
            itemStyle: {
              color: '#5DD4FD',
              borderRadius: [8, 8, 0, 0],
              // 禁用悬停时的样式变化
              emphasis: {
                color: '#5DD4FD',
                borderRadius: [4, 4, 0, 0],
              },
            },
            barWidth: (() => {
              if (data.length === 7) {
                return '20%';
              }
              if (data.length > 15) {
                return '60%';
              }
              return '8%';
            })(), // 减小柱子宽度
          },
        ],
        animation: true,
        animationDuration: 1500,
        animationEasing: 'cubicOut',
      };

      chartInstance.current.setOption(option);

      // 响应式调整
      const handleResize = () => {
        chartInstance.current.resize();
      };
      window.addEventListener('resize', handleResize);

      return function cleanup() {
        window.removeEventListener('resize', handleResize);
        chartInstance.current.dispose();
      };
    },
    [data, title, isPc],
  );

  return (
    <div
      ref={chartRef}
      style={{
        width: '100%',
        height: `${height}px`,
        backgroundColor: '#fff',
        borderRadius: '10px',
      }}
    />
  );
};

export default UserBarChart;
